package book.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/login.jsp")
public class CRememberMeFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        //从请求中获取所有的Cookie
        Cookie[] cookies = req.getCookies();
        //判断是否存在记住登录状态的Cookie
        for(Cookie cookie : cookies){
            if(cookie.getName().equals("rememberMe")){
                //记住登录状态存在且未超时，取出登录名
                String username = cookie.getValue();
                //设置用户已经登录：在会话中设置属性
                req.getSession().setAttribute("username",username);
                req.getSession().removeAttribute("msg");
                //跳转首页
                res.sendRedirect("index.jsp");
                return;
            }
        }
        //对登录页：login.jsp 放行
        chain.doFilter(req, res);
    }
}
